-module(rewrite).
-export([arg_rewrite/1]).
-import(cookie,[check_cookie/1]).
-include_lib("yaws/include/yaws_api.hrl").

login_pages() ->
	["/yaws/login.yaws", "/yaws/index.yaws", "/yaws/logout.yaws", "/yaws/register.yaws", "/yaws/register_validation.yaws"].
	
extensions() ->
	["css", "js", "jpg", "gif", "mp3", "swf"].
	
do_rewrite(A) ->
	Req = A#arg.req,
	{abs_path, Path} = Req#http_request.path,
	PositionQ = string:chr(Path, $?),
	PagePath = case PositionQ of
		0 -> Path;
		_ -> lists:sublist(Path, PositionQ-1)
		end,
	PositionD = string:chr(PagePath, $.),
	Ext = string:substr(PagePath, PositionD+1),
	case lists:member(Ext, extensions()) of
		true -> A;
		false -> 
			case lists:member(PagePath, login_pages()) of
				true ->
					A;
				false ->
					A#arg{
						req = Req#http_request{
							path = {abs_path, "/yaws/index.yaws"}},
						state = {abs_path, Path}
						}
			end
	end.
	
arg_rewrite(A) ->
	io:format("rewriting",[]),
	case check_cookie(A) of
		{ok, _Session, _Cookie} ->
			A;
		{error, _} ->
			do_rewrite(A)
	end.
